﻿using System;

namespace Basmus.ReadWrite
{
    public class NullableReaderWriter<TValue> : IReaderWriter<TValue?>
        where TValue:struct
    {
        private readonly IReaderWriter<TValue> _valueReaderWriter;
        
        public NullableReaderWriter(IReaderWriter<TValue> valueReaderWriter)
        {
            _valueReaderWriter = valueReaderWriter;
        }

        public ReadResult<TValue?> Read(String str)
        {
            if (!String.IsNullOrEmpty(str))
            {
                var readResult = _valueReaderWriter.Read(str);
                if (readResult.Successful)
                {
                    return ReadResult<TValue?>.Success(readResult.Value);
                }
            }
            return ReadResult<TValue?>.Success(null);
        }

        public string Write(TValue? value)
        {
            return value.HasValue ? value.Value.ToString() : string.Empty;
        }
    }
}